#ifndef __M_UTIL_H__
#define __M_UTIL_H__

#pragma once

#include "log.hpp"
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <vector>
#include <memory>
#include <mysql/mysql.h>
#include <jsoncpp/json/json.h>

struct mysql_util
{
    static MYSQL* mysql_create(const std::string& host, const std::string& user, const std::string& pwd, const std::string& db, uint16_t port = 3306)
    {
        MYSQL* mysql = mysql_init(nullptr);
        if (mysql == nullptr)
        {
            LOG(ERR, "mysql init failed");
            return nullptr;
        }
        LOG(INF, "mysql init success");

        if (mysql_real_connect(mysql, host.c_str(), user.c_str(), pwd.c_str(), db.c_str(), port, nullptr, 0) == nullptr)
        {
            LOG(ERR, "mysql connect failed, %s", mysql_error(mysql));
            mysql_destroy(mysql);
            return nullptr;
        }
        LOG(INF, "mysql connect success");

        if (mysql_set_character_set(mysql, "utf8") != 0)
        {
            LOG(ERR, "set client character failed, %s", mysql_error(mysql));
            mysql_destroy(mysql);
            return nullptr;
        }
        LOG(INF, "set client character success");

        //mysql_select_db(mysql, db.c_str());

        return mysql;
    }

    static bool mysql_execute(MYSQL* mysql, const std::string& sql)
    {
        if (mysql_query(mysql, sql.c_str()) != 0)
        {
            LOG(ERR, "%s", sql.c_str());
            LOG(ERR, "mysql excute failed, %s", mysql_error(mysql));
            //mysql_destroy(mysql);//user_table的析构函数会统一释放句柄
            return false;
        }
        LOG(INF, "mysql excute success");

        return true;
    }

    static void mysql_destroy(MYSQL* mysql)
    {
        if (mysql != nullptr)
            mysql_close(mysql);
    }
};

struct json_util
{
    //将结构化json对象转化为json格式字符串
    static bool serialize(const Json::Value& root, std::string& s)
    {
        Json::StreamWriterBuilder swb;
        std::unique_ptr<Json::StreamWriter> sw(swb.newStreamWriter());

        std::stringstream ss;
        if (sw->write(root, &ss) != 0)
        {
            LOG(ERR, "serialize failed");
            return false;
        }

        s = ss.str();
        return true;
    }

    //将json格式字符串转化为结构化json对象
    static bool deserialize(const std::string& s, Json::Value& root)
    {
        Json::CharReaderBuilder crb;
        std::unique_ptr<Json::CharReader> cr(crb.newCharReader());

        std::string err;
        if (!cr->parse(s.c_str(), s.c_str() + s.size(), &root, &err))
        {
            LOG(ERR, "deserialize failed, %s", err.c_str());
            return false;
        }

        return true;
    }
};

struct string_util
{
    static int split(const std::string& s, const std::string& sep, std::vector<std::string>& ret)
    {
        int pos, start = 0;
        while (start < s.size() && ((pos = s.find(sep, start)) != std::string::npos))
        {
            //起始位置就是分隔符的情况
            if (start == pos)
            {
                start += sep.size();
                continue;
            }
            ret.push_back(s.substr(start, pos - start));
            start = pos + sep.size();
        }
        if (start < s.size())//防止以分隔符结尾
            ret.push_back(s.substr(start, std::string::npos));
        return ret.size(); 
    }
};

struct file_util
{
    static bool read(const std::string& filename, std::string& body)
    {
        //1.打开文件
        std::ifstream ifs(filename, std::ios::binary);//二进制形式读取防止特殊字符和非文本格式文件
        if (!ifs.is_open())
        {
            LOG(ERR, "open %s file failed", filename.c_str());
            return false;
        }
        //2.获取文件大小
        int fsize;
        ifs.seekg(0, std::ios_base::end);//将读取位置移动到末尾
        fsize = ifs.tellg();//获取读取位置相对于起始位置的偏移量
        ifs.seekg(0, std::ios_base::beg);//将读取位置重新移动到起始位置
        //3.读取文件数据
        body.resize(fsize);
        ifs.read(&body[0], fsize);
        if (!ifs.good())//最近一次读取操作出错
        {
            LOG(ERR, "read %s file failed", filename);
            ifs.close();
            return false;
        }
        //4.关闭文件
        ifs.close();
        return true;
    }
};

#endif
